package com.yb.guigu.pick.security.filter;

import com.alibaba.fastjson2.JSONObject;
import com.yb.guigu.pick.security.generator.AuthenticationTokenGenerator;
import com.yb.guigu.pick.core.bean.GuiguResult;
import com.yb.guigu.pick.core.constant.GuiguStatus;
import com.yb.guigu.pick.core.constant.HttpConstant;
import com.yb.guigu.pick.cache.manager.api.GuiguPickStringCacheManager;
import com.yb.guigu.pick.security.bean.GuiguPickUser;
import com.yb.guigu.pick.core.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/18 15:01
 * FileName: XczxUserAuthenticationFilter
 * Description:
 */
@Slf4j
public class GuiguPickUserAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationTokenGenerator tokenGenerator;

    @Autowired
    GuiguPickStringCacheManager guiguPickStringCacheManager;

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/login",
            "POST");

    private static final AntPathRequestMatcher loginPathMatcher=DEFAULT_ANT_PATH_REQUEST_MATCHER;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //如果是登陆请求，则直接获取请求数据，放入request中
        if(loginPathMatcher.matches(request)){
            filterChain.doFilter(request,response);
            return;
        }


        String accessToken = request.getHeader(HttpConstant.AUTH_HEADER);


        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);


        if(!StringUtils.hasText(accessToken)){
            log.info("access_token is not present, so goto the next authenticationfilter");
            filterChain.doFilter(request,response);
            return;
        }

        String userStr = guiguPickStringCacheManager.getString(String.format(RedisKeyConstant.LOGIN_USER_DETAIL_KEY,accessToken));
        GuiguPickUser guiguPickUser = new GuiguPickUser();
        try {
            guiguPickUser= JSONObject.parseObject(userStr,GuiguPickUser.class);
        }catch (Exception e){
            log.error("guiguPickUser parse error:{}",e);
            response.getWriter().write(GuiguResult.error(GuiguStatus.HttpStatus.UNAUTHORIZED.getCode(),"token已失效，请重新登陆").toJSON());
            return;
        }

        if(Objects.isNull(guiguPickUser)){
            log.error("guiguPickUser parse error");
            response.getWriter().write(GuiguResult.error(GuiguStatus.HttpStatus.UNAUTHORIZED.getCode(),"token已失效，请重新登陆").toJSON());
            return;
        }
        //根据accessToken获取用户信息

        Authentication authenticated = tokenGenerator.authenticated(guiguPickUser);

        SecurityContextHolder.getContext().setAuthentication(authenticated);

        filterChain.doFilter(request,response);

    }
}
